<template>
  <div class="search-container">
    <mt-header :fixed="true">
      <router-link style="text-decoration: none;" to="/index" slot="left">
        <span class="iconfont icon-go-back"></span>
      </router-link>
    </mt-header>
    <div class="flex-item-center" style="padding: 10px 20px;">
      <div class="search-box">
        <span class="iconfont icon-sousuo"></span>
        <input class="search-inp" @input="showKeywordFun" v-model="keyword" placeholder="输入商家、商品名称" type="search">
      </div>
      <span class="search-text" @click="searchShops">搜索</span>
    </div>
    <div class="hot-list-box" v-if="keyword === ''&&searchHistoryList">
      <p class="hot-text">搜索历史</p>
      <div class="hot-item">
        <span class="item" v-for="(item, index) in searchHistoryList" :key="index"  @click="searchThis(item)">{{item}}</span>
      </div>
    </div>
    <div class="hot-list-box" v-if="keyword === ''">
      <p class="hot-text">热门搜索</p>
      <div class="hot-item">
        <span class="item" v-for="(item, index) in hotList" :key="index"  @click="searchThis(item.word)">{{item.word}}</span>
      </div>
    </div>
    <div v-else class="search-list">
      <p v-if="showKeyword" class="keyword">正在搜索 "{{keyword}}"</p>
       <template v-if="searchList.restaurantList.length > 0 && !no">
        <div class="restaurant flex-item-center" v-for="(item, index) in searchList.restaurantList" :key="index" @click="enterShop(item)">
            <img-format class="restaurant-img" :src="item.image_path" :size="90" />
            <div class="flex-row-sb-center" style="width: 100%;">
              <div>
                <p class="sup-text">
                  <span class="res-name ellipsis">{{item.name}}</span>
                  <span class="activities-tag" :style="{ backgroundColor: '#'+subitem.name_color}" v-for="(subitem, index) in item.tags" :key="index">{{subitem.name}}</span>
                </p>
                <span class="next-time">接受预定，{{item.next_business_time}}开始配送</span>
              </div>
              <span class="rating">评价: {{item.rating}}</span>
            </div>
        </div>
       </template>
      <template v-else-if="no">
        <div class="flex-row-center d" v-if="searchList.restaurantList.length === 0">
          <img :src="notUrl" class="i" />
          <div>
            <p class="n">附近没有搜索结果</p>
            <p class="c">换个关键词试试吧</p>
          </div>
        </div>
        <p class="t" v-if="searchList.restaurantList.length === 0">
          <span class="iconfont icon-tuijian"></span>为您推荐
        </p>
        <div style="background-color: #efefef;">
          <div v-for="item in recomendList" :key="item.id" class="r">
            <img-format :src="item.image_path" class="r-i" />
            <div class="r-l">
              <h2 class="r-h ellipsis">{{item.name}}</h2>
              <p class="r-p-s">
                <span class="iconfont icon-xingxing1" v-for="i in 5" :key="i"></span>
              </p>
              <div class="r-d flex-row-sb-center" >
                <p v-if="item.piecewise_agent_fee">
                  <span>￥{{item.piecewise_agent_fee.extra_fee}}起送</span>
                  <span class="iconfont icon-anjianfengexian"></span>
                  <span>{{item.piecewise_agent_fee.description}}</span>
                </p>
                <p>
                  <span>{{item.distance|distanceFormat}}</span>
                  <span class="iconfont icon-anjianfengexian"></span>
                  <span>{{item.order_lead_time}}分钟</span>
                </p>
              </div>
              <p class="r-st">
                <span v-for="(subItem, ind) in  item.support_tags" :key="ind" :style="{color: '#'+subItem.color, borderColor: '#'+subItem.border}" class="st">{{subItem.text}}</span>
              </p>
            </div>
          </div>
        </div>
      </template>
      <div v-if="!no">
        <my-words :words="searchList.words" :keyword="keyword" :click="searchT"/>
      </div>
    </div>
  </div>
</template>

<script>
import { getHotSearch, searchNearbyRestaurant, getRecommend, getCookie } from '@/api/elm-data'
import MyWords from './Words.vue'
 import ImgFormat from '_c/imgFormat/ImgFormat.vue'
 import { notFoundImg } from './'
export default {
  name: 'search-shop',
  data() {
    return {
      hotList: [],
      keyword: '',
      city_id: '',
      geo: {
        latitude: '',
        longitude: ''
      },
      searchList: {
        words: [],
        restaurantList: []
      },
      showKeyword: false,
      timeout: undefined,
      no: false,
      notUrl: notFoundImg,
      recomendList:[],
      searchHistoryList: undefined
    }
  },
  async created() {
    this.city_id = window.sessionStorage.getItem('city_id')
    this.geo = JSON.parse(window.sessionStorage.getItem('Geo'))
    const { data } = await getHotSearch(JSON.parse(window.sessionStorage.getItem('Geo')))
    this.hotList = data
    const searchHistory = JSON.parse(window.localStorage.getItem('SEARCH_HISTORY'))
    if(searchHistory) {
      this.searchHistoryList = searchHistory
    }
  },
  methods: {
    showKeywordFun() {
      this.showKeyword = true
      if(!this.timeout) {
        this.timeout = setTimeout(() => {
          this.showKeyword = false
          clearTimeout(this.timeout)
          this.timeout = undefined
        }, 500)
      }
    },
    async enterShop(item) {
      if(item.type === 0) {
        this.$router.push({ name: 'shopcommodity1', query: {
          shopId: item.id,
          is_session: true
        }})
      }else if(item.type === 1) {
        const { data: { data: { cookies} } } = await getCookie()
        cookies.forEach(item => {
          document.cookie = item.name + '=' + item.value + ';'
        })

        this.$router.push({ name: 'shopcommodity2', query: {
          shopId: item.id,
          is_session: true
        }})
      }
    },
    async searchShops() {
      const searchHistory = JSON.parse(window.localStorage.getItem('SEARCH_HISTORY'))
      if(searchHistory) {
        searchHistory.push(this.keyword)
        window.localStorage.setItem('SEARCH_HISTORY', JSON.stringify(searchHistory))
      }else {
        window.localStorage.setItem('SEARCH_HISTORY', JSON.stringify([this.keyword]))
      }

      const { data } = await searchNearbyRestaurant(this.keyword, this.city_id,this.geo)
      // console.log(data)
      this.no = true
      if(data.restaurants.length > 0 ) {
        this.recomendList = data.restaurants
      }else {
        const { data } = await getRecommend({
          keyword: this.keyword,
          latitude: this.geo.latitude,
          longitude: this.geo.longitude
        })
        console.log(data)
        data.inside[1].restaurant_with_foods.forEach(item => {
          this.recomendList.push(item.restaurant)
        })
      }
    },
    searchThis(item) {
      this.keyword = item
    },
    searchT(a) {
      console.log(a)
      this.keyword = a
    }
  },
  components: {
    MyWords,
    ImgFormat
  },
  watch: {
    async keyword() {
      if(this.keyword !== '') {
        this.recomendList = []
        this.no = false
        try {
          const { data } = await searchNearbyRestaurant(this.keyword, this.city_id, this.geo)
            this.searchList.words = data.words
            this.searchList.restaurantList = data.restaurants
            console.log(this.searchList.restaurantList)
          }catch(e) {
            if(e.response.data.name === 'UNAUTHORIZED') {
              this.$toast('账号失效，请重新登录')
              this.$router.replace('/login')
              return
            }
          }
        }

    }
  }
}
</script>

<style scoped lang="less">
  .search-container {
    background-color: #fff;
    width: 100vw;
    min-height: 100vh;
    padding-top: 80px;
  }
  .mint-header {
    background-color: transparent;
  }
  .icon-go-back {
    color: #8f8f8f;
    font-size: 32px;
  }
  .search-box {
    position: relative;
    width: 100%;
  }
  .icon-sousuo {
    position: absolute;
    left: 10px;
    top: 10px;
    font-size: 30px;
  }
  .search-inp {
    box-sizing: border-box;
    width: 610px;
    padding: 10px 0 10px 40px;
    border: none;
    background-color: #f8f8f8;
    font-size: 28px;
  }
  .search-text {
    font-weight: 600;
    font-size: 30px;
    white-space: nowrap;
  }
  .hot-list-box {
    padding: 20px;
  }
  .hot-text {
    font-size: 30px;
    color: #666666;
    font-weight: 600;
  }
  .hot-item {
    display: flex;
    flex-wrap: wrap;
  }
  .item {
    padding: 10px 20px;
    margin: 0 30px 30px 0;
    background-color: #f7f7f7;
    color: #797979;
  }
  .keyword {
    padding-left: 20px;
    font-size: 26;
    color: #666666;
  }
  .restaurant {
    padding: 10px 20px;
    border-bottom: 1px solid #eee;
  }
  .restaurant-img {
    width: 100px;
    margin-right: 20px;
  }
  .sup-text {
    margin-top: 0;
    margin-bottom: 10px;
    font-size: 28px;
  }
  .next-time {
    padding: 1px 5px;
    border: 1px solid #00D762;
    border-radius: 15px;
    font-size: 22px;
    color: #00D762;
  }
  .res-name {
    display: inline-block;
    max-width: 300px;
    vertical-align: sub;
  }
  .activities-tag {
    display: inline-block;
    margin: 0 5px;
    padding: 0 2px;
    color: #fff;
    font-size: 24px;
  }
  .rating {
    color: #888;
  }
  .d {
    padding: 20px;
  }
  .i {
    width: 30%;
  }
  .n {
    margin: 0 20px;
    font-size: 32px
  }
  .c {
    margin: 10px 20px;
    font-size: 22;
    color: #666;
  }
  .t {
    margin: 0;
    padding: 20px;
    text-align: center;
    font-size: 32px;
    font-weight: 600;
    background-color: #f8f8f8;
    color: #444;
    position: relative;
    &::before {
      content: '';
      position: absolute;
      width: 50px;
      height: 1px;
      top: 50%;
      left: 240px;
      background-color: #555;
    }
    &::after {
      content: '';
      position: absolute;
      width: 50px;
      height: 1px;
      top: 50%;
      right: 240px;
      background-color: #555;
    }
  }
  .icon-tuijian {
    font-size: 32px;
  }
  .r {
    display: flex;
    align-items: flex-start;
    padding: 20px;
    margin-bottom: 20px;
    background-color: #fff;
  }
  .r-i {
    flex: 1;
  }
  .r-l {
    box-sizing: border-box;
    padding-left: 20px;
    flex: 4;
  }
  .r-h {
    margin: 0;
    font-size: 32px;
    width: 100%;
  }
  .r-p-s {
    margin: 10px 0;
    color: #efefef;
  }
  .r-d {
    font-size: 24px;
    color: #666;
  }
  .r-st {
    display: flex;
    flex-wrap: wrap;
  }
  .st {
    display: inline-block;
    padding: 2px 5px;
    margin: 5px;
    border: 1px solid transparent;
    font-size: 18px;
  }
</style>
